var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var  jwtAuth  =require('./util/jwt.js')

//jwt 验证
// const jwtAuth  =require('./util/jwt')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const adminRouter = require('./routes/admin');
const salesRouter = require('./routes/sales');
const classifysRouter = require('./routes/classifys');
const productsRouter = require('./routes/products');
const ordersRouter = require('./routes/orders');
const customersRouter = require('./routes/customers');
const claimsRouter = require('./routes/claims');
const imagesRouter = require('./routes/images')


var app = express();

// CORS：设置允许跨域中间件
var allowCrossDomain = function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type,Accept,Authorization");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
};
app.use(allowCrossDomain); // 使用该中间件

const mongoose = require('mongoose');
// 设置要连接的 MongoDB 服务器地址(studentsManage:要连接的数据库名称)
const dbURI = 'mongodb://localhost:27017/insuranceSystem';
// 连接数据库
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('connected', () => console.log(dbURI + ' 数据库连接成功'));




// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//jwt验证

// app.use(jwtAuth)


app.use('/', indexRouter);
app.use('/users', usersRouter);
//管理员一级路径
app.use('/admins', adminRouter);
//销售员一级路径
app.use('/sales', salesRouter);
//保险分类一级路径
app.use('/classifys', classifysRouter);
//产品分类一级路径
app.use('/products', productsRouter);
//订单管理一级路径
app.use('/orders', ordersRouter);
//客户一级路径
app.use('/customers', customersRouter);
//理赔一级路径
app.use('/claims', claimsRouter);
// 图片一级路径
app.use('/images', imagesRouter);






// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

app.listen(3000, () => console.log('3000启动成功'))
